from google.appengine.ext import db

from lib.webapp import app, render_context, render, MJRequestHandler
from os.path import join

import lib.waypoints as wp
import lib.regions as r

import sys
import logging


from lib.webapp import app

log = logging.getLogger(__name__)

from django import newforms as forms


class ctl_WayPoint(MJRequestHandler):

  path = "/waypoints"


  def load_region(self):  
    log.debug( "enter load_region" )
    regions = dict()
    region = self.request.get( "region", None )
    regions[0] = self.request.get( "region0", None )
    regions[1] = self.request.get( "region1", None )
    regions[2] = self.request.get( "region2", None )
    
    if( region == None or region == "" ):
        log.debug( "no region, search in tree" )
        for rl in range(2,-1,-1):
            log.debug( "    search in %d" % rl )
            if( regions[rl] != None ):
                log.debug( "   found!" )
                region = regions[rl]
                break
                
        if( region == None or region == "" ):
            return True
            
    def load( rkey ):                
        try:
            log.debug( "load region for %s" % rkey )
            rout = db.GqlQuery( "select * from Region where __key__ = :1", db.Key(rkey)  ).fetch(1)[0]
            log.debug( "    loaded" )
            return rout
        except:
            self.redirect( "/error?msg=Wrong region key" )
            return None

    self.c.wp.region = load( region )
    
    if( self.c.wp.region == None ):
        return False

    log.debug( "check region" )
    if( self.c.wp.region.check_tree( regions[0], regions[1], regions[2] ) ):
        return True

    log.debug( "check region2" )

    for rl in range(2,-1,-1):
        log.debug( "   check in %d" % rl )
        if( regions[rl] != None ):
            self.c.wp.region = load( regions[rl] )
                    
            if( self.c.wp.region == None ):
                return False
            
            if( self.c.wp.region.check_tree( regions[0], regions[1], regions[2] ) ):
                return True
    log.debug( "leaving load_region" )
    return True

  def load_journey(self):  

    journey = self.request.get( "journey", None )
    log.debug( "journey = %s" % journey )
    if( None == journey ):
        self.redirect( "/error?msg=no_journey" )
        
        return False
        
    try:
        self.c.j = db.GqlQuery( "select * from Journey where __key__ = :1", db.Key(journey)  ).fetch(1)[0]
        log.debug( "loaded journey for %s(%s)" % ( journey, self.c.j.key() ) )
    except:
        self.redirect( "/error?msg=wrng_journey" )
        return False

    return True

  def load_waypoint(self):  

    wp = self.request.get( "wp", None )
    
    if( None == wp or wp == ""):
        #self.redirect( "/error?msg=no_wp" )
        return False
        
    try:
        self.c.wp = db.GqlQuery( "select * from WayPoint where __key__ = :1", db.Key(wp)  ).fetch(1)[0]
        log.debug( "loaded waypoint for %s" % wp )
    except:
        self.redirect( "/error?msg=wrng_wp" )
        return False

    return True
    
  def movup(self):
      
    if( not self.load_journey() ):
        return

    if( not self.load_waypoint() ):
        return
    
    try:    
        awp = db.GqlQuery( "select * from WayPoint where journey = :1 and pos = :2", self.c.j, self.c.wp.pos - 1 ).fetch(1)[0]
        awp.pos += 1
        self.c.wp.pos -= 1
        awp.put()
        self.c.wp.put()
        self.redirect( "/waypoints/?journey=%s" % self.c.j.key() )
        return 
    except Exception, e:
        log.exception( str(e) )
        self.redirect( "/waypoints/?journey=%s" % self.c.j.key() )
        return
      
  def movdown(self):


    if( not self.load_waypoint() ):
        return
    
    try:    
        awp = db.GqlQuery( "select * from WayPoint where journey = :1 and pos = :2", self.c.j, self.c.wp.pos + 1 ).fetch(1)[0]
        awp.pos -= 1
        self.c.wp.pos += 1
        awp.put()
        self.c.wp.put()
        self.redirect( "/waypoints/?journey=%s" % self.c.j.key() )
        return 
    except Exception, e:
        log.exception( str(e) )
        self.redirect( "/waypoints/?journey=%s" % self.c.j.key() )
        return

  def view(self):
      
    if( not self.load_waypoint() ):
        return
    
    self.c.j = self.c.wp.journey
    return self.render( "/en/viewwaypoint.html" )      

  def add(self):

    self.c.edit = False

    if( None != self.request.get( "journey", None ) ):
        if( not self.load_journey() ):
            return

    if( not self.load_waypoint() ):
        self.c.wp = wp.WayPoint()
    else:
        self.c.edit = True

    if( None != self.request.get( "region", None ) ):
        if( not self.load_region() ):
            return
        
    if( "" != self.c.wp.safe_key() and self.c.j.key() != self.c.wp.journey.key() ):
        log.warning( "journey and waypoint's journey mismatch %s<=>%s" %( self.c.j.key(), self.c.wp.journey.key() ) )
        return(self.redirect("/waypoints?journey=%s" % self.c.j.key() ))
        
    if( self.c.j.user != self.c.user ):
        log.warning( "journey is not of current user" )
        return(self.redirect("/waypoints?journey=%s" % self.c.j.key() ))
    
    action  = self.request.get( "action", None )
    desc    = self.request.get( "desc", None )
    coords  = self.request.get( "coords", None )
    arrived = self.request.get( "arrived", None )
    leaved  = self.request.get( "leaved", None )
    icon    = self.request.get( "icon", 0 )

    if( not icon in ["0","1"] ):
        icon = 0
    else:
        icon = int(icon)
    
    self.c.wp.icon = icon

    # check parameters
    
    if( desc != None and desc != "" ):
        if( len( desc ) > 700 ):
            self.c.wp.desc = desc[0:699]
        else:
            self.c.wp.desc = desc

    self.c.wp.arrived = self.to_datetime( arrived, "Arrived" )
    self.c.wp.leaved  = self.to_datetime( leaved,  "Finished on" )
    
    try:        
        self.c.wp.coords = coords
    except:
        self.c.errors = True
        self.c.msg["Coordinates"] = "should be in format 'latitude,longitude'!"
    
    if( self.c.errors ):
        return self.render( "/en/editwaypoint.html" )
    
    if( not self.c.edit ):
        self.c.wp.journey = self.c.j
        if( self.c.j.last_wp == None ):
            self.c.j.last_wp = 0
        self.c.wp.pos = self.c.j.last_wp + 1
    
    if( None != action ):
        self.c.wp.put()

        if( not self.c.edit ):
            self.c.j.last_wp = self.c.wp.pos
            self.c.j.put()
           
        return(self.redirect("/waypoints?journey=%s" % self.c.j.key() ))
    else:
        self.c.regions = r.load_regions_for(self.c.wp.region)
        return self.render( "/en/editwaypoint.html" )
        

      
  def edit(self):

    try:
        
        if( not self.load_journey() ):
            return

        if( not self.load_waypoint() ):
            return

        if( "" != self.c.wp.safe_key() and self.c.j.key() != self.c.wp.journey.key() ):
            log.warning( "journey and waypoint's journey mismatch" )
            return(self.redirect("/waypoints?journey=%s" % self.c.j.key() ))
            
        if( self.c.j.user != self.c.user ):
            log.warning( "journey is not of current user" )
            return(self.redirect("/waypoints/view?journey=%s&wp=%s" % (self.c.j.key(),self.c.wp.key() )))

        # set default region of journey, if journey supplied
        if( self.c.wp.region == None and self.c.j != None):
            self.c.wp.region = self.c.j.region

        self.c.regions = r.load_regions_for( self.c.wp.region )
       
        return(self.render("/en/editwaypoint.html"))

    finally:
        log.debug( "leave edit handler" )

  def new(self):

        if( not self.load_journey() ):
            return

        self.c.wp = wp.WayPoint()
        
        if( self.c.j ):
            self.c.wp.region = self.c.j.region    
        self.c.regions = r.load_regions_for(self.c.wp.region)
 
        return(self.render("/en/editwaypoint.html"))

  def index(self):

    if( not self.load_journey() ):
        return
        
    self.c.wp = wp.WayPoint()    
            
    return(self.render("/en/waypoints.html"))

  def __init__(self):

      
        MJRequestHandler.__init__(self)
      
        self.add_handler( "/add", self.add )
        self.add_handler( "/new", self.new )
        self.add_handler( "/edit", self.edit )
        self.add_handler( "/movup", self.movup )
        self.add_handler( "/movdown", self.movdown )
        self.add_handler( "/view", self.view, False )

        self.c.regions = dict()
        self.c.region_tree = dict()

 

app().add_handler( ctl_WayPoint.path + ".*", ctl_WayPoint )
